package com.xdy.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xdy.reggie.common.CustomException;
import com.xdy.reggie.dto.DishDto;
import com.xdy.reggie.entity.Category;
import com.xdy.reggie.entity.Dish;
import com.xdy.reggie.entity.DishFlavor;
import com.xdy.reggie.mapper.DishMapper;
import com.xdy.reggie.service.CategoryService;
import com.xdy.reggie.service.DishFlavorService;
import com.xdy.reggie.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class DishServiceImpl extends ServiceImpl<DishMapper, Dish> implements DishService {

    @Resource
    private DishFlavorService dishFlavorService;

    @Resource
    private CategoryService categoryService;

    @Override
    @Transactional
    public void saveWithFlavor(DishDto dishDto) {
        //先查询是否存在已删除的同名菜品
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Dish::getName,dishDto.getName());
        Dish one = getOne(queryWrapper);
        List<DishFlavor> flavors = dishDto.getFlavors();
        if (one != null && one.getIsDeleted() == 1){
            BeanUtils.copyProperties(dishDto,one,"id");
            updateIsDeleted(one);
            LambdaQueryWrapper<DishFlavor> dishFlavorLambdaQueryWrapper = new LambdaQueryWrapper<>();
            dishFlavorLambdaQueryWrapper.eq(DishFlavor::getDishId,one.getId());
            dishFlavorService.remove(dishFlavorLambdaQueryWrapper);
            flavors = flavors.stream().map(item -> {
                item.setDishId(one.getId());
                return item;
            }).collect(Collectors.toList());
        }else{
            baseMapper.insert(dishDto);
            flavors = flavors.stream().map(item -> {
                item.setDishId(dishDto.getId());
                return item;
            }).collect(Collectors.toList());
        }
        dishFlavorService.saveBatch(flavors);
    }

    /**
     * 该菜品已删除，重新添加
     * @param one
     */
    private void updateIsDeleted(Dish one) {
        one.setIsDeleted(0);
        updateById(one);
    }

    @Override
    public Page<DishDto> getWithCategoryName(Page<Dish> dishPage,String name) {
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Dish::getIsDeleted,0);
        queryWrapper.like(name != null,Dish::getName,name);
        queryWrapper.orderByDesc(Dish::getUpdateTime);
        page(dishPage, queryWrapper);
        List<Dish> records = dishPage.getRecords();
        Page<DishDto> pageInfo = new Page<>();
        //拷贝第一次查出的分页信息，里面的数据只有菜品分类的ID，需要再次查询出菜品分类名称
        BeanUtils.copyProperties(dishPage,pageInfo,"records");
        List<DishDto> records2 = records.stream().map(item -> {
            Long categoryId = item.getCategoryId();
            //通过菜品分类id查询菜品分类信息
            Category category = categoryService.getById(categoryId);
            DishDto dishDto = new DishDto();
            if (category != null){
                //设置菜品分类名称
                dishDto.setCategoryName(category.getName());
            }
            //拷贝原来的Dish中的数据到DishDto
            BeanUtils.copyProperties(item,dishDto);
            return dishDto;
        }).collect(Collectors.toList());
        //设置加工后的records
        pageInfo.setRecords(records2);
        return pageInfo;
    }

    @Override
    public DishDto getWithFlavorByDishId(Long id) {
        //获取菜品信息
        Dish dish = getById(id);
        //获取菜品口味信息
        LambdaQueryWrapper<DishFlavor> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(DishFlavor::getDishId,id);
        List<DishFlavor> dishFlavors = dishFlavorService.list(queryWrapper);
        DishDto dishDto = new DishDto();
        BeanUtils.copyProperties(dish,dishDto);
        dishDto.setFlavors(dishFlavors);
        return dishDto;
    }

    @Override
    @Transactional
    public void updateWithFlavor(DishDto dishDto) {
        //修改菜品信息
        updateById(dishDto);
        //删除相关菜品的口味信息，再添加新的口味信息
        LambdaQueryWrapper<DishFlavor> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(DishFlavor::getDishId,dishDto.getId());
        //删除相关菜品的口味信息
        dishFlavorService.remove(queryWrapper);
        //添加新的菜品口味
        List<DishFlavor> flavors = dishDto.getFlavors();
        flavors = flavors.stream().map(item -> {
            item.setDishId(dishDto.getId());
            return item;
        }).collect(Collectors.toList());
        dishFlavorService.saveBatch(flavors);
    }

    @Override
    @Transactional
    public void removeWithDishFlavor(List<Long> ids) {
        log.info("删除的id ===> {}",ids);
        log.info("菜品ID ===> {}",ids);
        List<Dish> dishes = listByIds(ids);
        boolean allMatch = dishes.stream().allMatch(item -> item.getStatus() == 0);//判断要删除的菜品是否都是停售状态
        if (!allMatch){
            throw new CustomException("菜品正在售卖，请先停售！");
        }
        List<DishFlavor> dishFlavors = new ArrayList<>();
        List<Dish> dishList = ids.stream().map(item -> {
            Dish dish = new Dish();
            DishFlavor dishFlavor = new DishFlavor();
            dish.setId(item);
            dish.setIsDeleted(1);
            dishFlavor.setDishId(item);
            dishFlavor.setIsDeleted(1);
            dishFlavors.add(dishFlavor);
            return dish;
        }).collect(Collectors.toList());
        updateBatchById(dishList);
        for (DishFlavor dishFlavor : dishFlavors) {
            LambdaQueryWrapper<DishFlavor> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(DishFlavor::getDishId,dishFlavor.getDishId());
            dishFlavorService.update(dishFlavor,queryWrapper);
        }
    }
}
